using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.Profile;
using System.Web.UI.WebControls;
using System.Resources;
using System.Collections.Specialized;
using System.Reflection;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using IWCommunity.WebControls.HIP;
using IWCommunity.Common;


namespace IWCommunity.WebControls
{
    public class MembershipRequestControl : CreateUserWizard
    {
        enum CharMix { upper, lower, mix }

        #region Fields
        protected string[] _randCharacters = { "A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z",
                "2","3","4","5","6","7","8","9",
                "a","b","c","d","e","f","g","h","j","k","m","n","p","q","r","s","t","u","v","w","x","y","z"};
        private string _HipInstructionsLabelText = string.Empty;
        private string _HipPictureLabelText = string.Empty;
        private string _HipPictureDescription = string.Empty;
        private string _HipCharactersLabelText = string.Empty;
        private string _HipErrorMessage = string.Empty;
        private string _HipResetLabelText = string.Empty;
        private string _FirstNameLabelText = String.Empty;
        private string _LastNameLabelText = string.Empty;
        private string _companyLabelText = string.Empty;
        private string _telephoneLabelText = string.Empty;
        private string _jobTitleLabelText = string.Empty;
        private string _defaultRole = string.Empty;
        private string _FirstNameRequiredErrorMessage = String.Empty;
        private string _LastNameRequiredErrorMessage = String.Empty;
        #endregion

        #region Controls
        //HIP controls
        protected ImageHipChallenge imgHip;
        protected HipValidator vldHip;
        protected TextBox txtHip;
        protected Label lblHipPicture;
        protected Label lblHipCharacters;
        protected Label lblHipInstructions;
        protected Label lblHipPictureDescription;
        protected LinkButton lnkHip;
        protected TextBox txtFirstName;
        protected TextBox txtLastName;
        protected TextBox txtCompany;
        protected TextBox txtTel;
        protected TextBox txtJobTitle;
        #endregion

        #region Properties
        public string HipInstructionsLabelText
        {
            get { return _HipInstructionsLabelText; }
            set { _HipInstructionsLabelText = value; }
        }

        public string HipPictureLabelText
        {
            get { return _HipPictureLabelText; }
            set { _HipPictureLabelText = value; }
        }

        public string HipPictureDescription
        {
            get { return _HipPictureDescription; }
            set { _HipPictureDescription = value; }
        }

        public string HipCharactersLabelText
        {
            get { return _HipCharactersLabelText; }
            set { _HipCharactersLabelText = value; }
        }

        public string HipErrorMessage
        {
            get { return _HipErrorMessage; }
            set { _HipErrorMessage = value; }
        }

        public string HipResetLabelText
        {
            get { return _HipResetLabelText; }
            set { _HipResetLabelText = value; }
        }
        public string FirstNameLabelText
        {
            get { return _FirstNameLabelText; }
            set { _FirstNameLabelText = value; }
        }

        public string LastNameLabelText
        {
            get { return _LastNameLabelText; }
            set { _LastNameLabelText = value; }
        }

        public string CompanyLabelText
        {
            get { return _companyLabelText; }
            set { _companyLabelText = value; }
        }

        public string TelephoneLabelText
        {
            get { return _telephoneLabelText; }
            set { _telephoneLabelText = value; }
        }

        public string JobTitleLabelText
        {
            get { return _jobTitleLabelText; }
            set { _jobTitleLabelText = value; }
        }

        public string FirstNameRequiredErrorMessage
        {
            get { return _FirstNameRequiredErrorMessage; }
            set { _FirstNameRequiredErrorMessage = value; }
        }

        public string LastNameRequiredErrorMessage
        {
            get { return _LastNameRequiredErrorMessage; }
            set { _LastNameRequiredErrorMessage = value; }
        }

        public string FirstName
        {
            get { return txtFirstName.Text; }
            set { txtFirstName.Text = value; }
        }

        public string LastName
        {
            get { return txtLastName.Text; }
            set { txtLastName.Text = value; }
        }

        public string Telephone
        {
            get { return txtTel.Text; }
            set { txtTel.Text = value; }
        }

        public string Company
        {
            get { return txtCompany.Text; }
            set { txtCompany.Text = value; }
        }

        public string JobTitle
        {
            get { return txtJobTitle.Text; }
            set { txtJobTitle.Text = value; }
        }

        public string DefaultRole
        {
            get { return _defaultRole; }
            set { _defaultRole = value; }
        }

        #endregion

        #region Rendering Methods
        private Table GetCreateUserTable()
        {
            Table tblResult = null;
            Table outertbl = this.CreateUserStep.ContentTemplateContainer.Controls[0] as Table;
            if (outertbl != null)
            {
                Table innertbl = outertbl.Rows[0].Cells[0].Controls[0] as Table;
                if (innertbl != null)
                {
                    tblResult = innertbl;
                }
            }
            return tblResult;
        }

        /// <summary>
        ///     Adds a field and label to the CreateUserWizard control
        /// </summary>
        /// <param name="prompt"></param>
        /// <param name="controlName"></param>
        /// <param name="requiredValuePrompt"></param>
        /// <returns></returns>
        private TableRow AddField(string prompt, Control ctrl, string requiredValuePrompt)
        {
            TableRow tr1 = new TableRow();
            TableCell td1 = new TableCell();
            TableCell td2 = new TableCell();
            Label lblPrompt = new Label();
            TextBox txtField = ctrl as TextBox;
            lblPrompt.Text = prompt;
            lblPrompt.AssociatedControlID = ctrl.ID;
            td1.Controls.Add(lblPrompt);
            td1.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(txtField);
            tr1.Cells.Add(td1);
            tr1.Cells.Add(td2);
            if (requiredValuePrompt != null)
            {
                RequiredFieldValidator rfv = new RequiredFieldValidator();
                rfv.ControlToValidate = txtField.ID;
                rfv.ID = "rfv" + txtField.ID;
                rfv.ValidationGroup = this.ID;
                rfv.Text = requiredValuePrompt;
                td2.Controls.Add(rfv);
            }
            return tr1;
        }

        private void AddHipControls()
        {
            Table cuwTable = GetCreateUserTable();
            TableRow tr;
            TableCell td;
            TableCell td2;

            lblHipInstructions = new Label();
            lblHipInstructions.Text = HipInstructionsLabelText;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
           // td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lblHipInstructions);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.AddAt(14, tr);

            lblHipPicture = new Label();
            lblHipPicture.Text = HipPictureLabelText;
            StringCollection scWords = new StringCollection();
            string randString = GenerateRandomString(6, CharMix.mix);
            scWords.Add(randString);
            imgHip = new ImageHipChallenge();
            imgHip.ID = "imgHip";
            imgHip.Width = Unit.Pixel(210);
            imgHip.Height = Unit.Pixel(70);
            imgHip.Words = scWords;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipPicture);
            td2.Controls.Add(imgHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.AddAt(15, tr);

            lblHipPictureDescription = new Label();
            lblHipPictureDescription.Text = HipPictureDescription;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            //td2.HorizontalAlign = HorizontalAlign.Center;
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.Controls.Add(lblHipPictureDescription);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.AddAt(16, tr);

            txtHip = new TextBox();
            txtHip.ID = "txtHip";
            txtHip.MaxLength = 20;
            lblHipCharacters = new Label();
            lblHipCharacters.Text = HipCharactersLabelText;
            vldHip = new HipValidator();
            vldHip.ID = "vldHip";
            vldHip.Display = ValidatorDisplay.Static;
            vldHip.ControlToValidate = txtHip.ID;
            vldHip.ValidationGroup = this.ID;
            vldHip.HipChallenge = imgHip.ID;
            vldHip.Text = HipErrorMessage;
            vldHip.ErrorMessage = HipErrorMessage;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            td.HorizontalAlign = HorizontalAlign.Right;
            td2.HorizontalAlign = HorizontalAlign.Left;
            td.Controls.Add(lblHipCharacters);
            td2.Controls.Add(txtHip);
            td2.Controls.Add(vldHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.AddAt(17, tr);

            lnkHip = new LinkButton();
            lnkHip.Click += new EventHandler(lnkHip_Click);
            lnkHip.Text = HipResetLabelText;
            lnkHip.CausesValidation = false;

            tr = new TableRow();
            td = new TableCell();
            td2 = new TableCell();
            //td2.HorizontalAlign = HorizontalAlign.Center;
            td2.Controls.Add(lnkHip);
            tr.Cells.Add(td);
            tr.Cells.Add(td2);
            cuwTable.Rows.AddAt(18, tr);
        }

        private void AddNameFields()
        {
            //Add Extra Fields
            txtFirstName = new TextBox();
            txtFirstName.ID = "txtFirstName";
            txtLastName = new TextBox();
            txtLastName.ID = "txtLastName";
            TableRow tr1 = AddField(FirstNameLabelText, txtFirstName, FirstNameRequiredErrorMessage);
            TableRow tr2 = AddField(LastNameLabelText, txtLastName, LastNameRequiredErrorMessage);
            Table cuwTable = GetCreateUserTable();
            cuwTable.Rows.AddAt(3, tr1);
            cuwTable.Rows.AddAt(4, tr2);
        }

        private void AddPersonalFields()
        {
            //Add Extra Fields
            txtTel = new TextBox();
            txtTel.ID = "txtTel";
            txtCompany = new TextBox();
            txtCompany.ID = "txtCompany";
            txtJobTitle = new TextBox();
            txtJobTitle.ID = "txtJobTitle";

            TableRow tr1 = AddField(CompanyLabelText, txtCompany, null);
            TableRow tr2 = AddField(JobTitleLabelText, txtJobTitle, null);
            TableRow tr3 = AddField(TelephoneLabelText, txtTel, null);
            Table cuwTable = GetCreateUserTable();
            cuwTable.Rows.AddAt(5, tr1);
            cuwTable.Rows.AddAt(6, tr2);
            cuwTable.Rows.AddAt(7, tr3);
        }

        protected override void CreateControlHierarchy()
        {
            base.CreatedUser += new EventHandler(MembershipRequestControl_CreatedUser);
            base.CreateControlHierarchy();
            AddNameFields();
            AddPersonalFields();
            AddHipControls();
        }

       
        void MembershipRequestControl_CreatedUser(object sender, EventArgs e)
        {

            //TextBox UserNameTextBox = (TextBox)CreateUserWizardStep2.ContentTemplateContainer.FindControl("UserName");
            string currentUserName = ((MembershipRequestControl)(sender)).UserName;
            string firstName = ((MembershipRequestControl)(sender)).FirstName;
            string lastName = ((MembershipRequestControl)(sender)).LastName;
            string company = ((MembershipRequestControl)(sender)).Company;
            string jobTitle = ((MembershipRequestControl)(sender)).JobTitle;
            string telephone = ((MembershipRequestControl)(sender)).Telephone;
            string emailAddress = ((MembershipRequestControl)(sender)).Email;

            try
            {
                //throw new Exception("The method or operation is not implemented.");
                if (DefaultRole.Length > 0)
                {

                    System.Web.Security.Roles.AddUserToRole(currentUserName, DefaultRole);
                }
            }
            catch (Exception ex)
            {

                Logger.LogError(ex,"Error trying to add new user to " + DefaultRole + " role");
            }

            try
            {
                //test straight UserName

                //attempt to get membership user, if we can, then lets get profile for user
                MembershipUser currentUser = Membership.GetUser(currentUserName); //get current logged on user
                if (currentUser != null)
                {
                    //update user profile
                    ProfileBase userProfile = DefaultProfile.Create(currentUser.UserName);
                    userProfile.SetPropertyValue("FirstName", firstName);
                    userProfile.SetPropertyValue("LastName", lastName);

                    if (company.Length > 0)
                        userProfile.SetPropertyValue("Company", company);
                    if (jobTitle.Length > 0)
                        userProfile.SetPropertyValue("JobTitle", jobTitle);
                    if (telephone.Length > 0)
                        userProfile.SetPropertyValue("Telephone", telephone);

                    userProfile.Save();
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex,"Error in membershiprequest control, trying to set profile properties");
            }

            
            try
            {
                //emailAddress = "administrator@test.com";
                if (emailAddress.Length > 0)
                {
                    Hashtable xsltArguments = new Hashtable();
                    xsltArguments["userName"] = currentUserName;
                    IWCommunity.WebControls.Email.SendEmail(SPContext.Current.Web,emailAddress, SPContext.Current.Web.Url + "/_layouts/IWCommunity/emails/MembershipApproved.xslt",xsltArguments);
                }
            }
            catch (Exception ex)
            {
                Logger.LogError(ex,"Error sending email to newly created user");
            }

           
        }

        //protected override void OnCreatingUser(LoginCancelEventArgs e)
        //{
        //    SPWeb web = SPControl.GetContextWeb(Context);
        //    if (web.Features[new Guid("{69CE2076-9A2F-4c71-AEDF-F4252C01DE4E}")] != null)
        //    {
        //        MembershipRequest request = new MembershipRequest();
        //        request.UserEmail = this.Email;
        //        request.UserName = this.UserName;
        //        request.PasswordQuestion = this.Question;
        //        request.PasswordAnswer = this.Answer;
        //        request.FirstName = this.FirstName;
        //        request.LastName = this.LastName;
        //        //MembershipRequest.CopyToReviewList(request);
        //        //TODO:add code to create user account
        //        //this.MoveTo(this.CompleteStep);
        //        base.OnCreatingUser(e);
        //    }
        //    else
        //    {
        //        //this will create user normally, without need for custom creation code. But might not create first and last name
        //        //TODO:check this!!
        //        base.OnCreatingUser(e);
        //    }
        //}

       
        #endregion

        #region Events
        void lnkHip_Click(object sender, EventArgs e)
        {
            //Nothing to do, the image will reset automatically
        }

        private string GenerateRandomString(int NumAlphs, CharMix Mix)
        {
            Random rGen = new Random();

            int iMix = (int)Mix;

            int p = 0;
            string sPass = "";
            int iCharMax = 32;
            if (iMix > 0) iCharMax = 55;
            for (int x = 0; x < NumAlphs; x++)
            {
                p = rGen.Next(0, iCharMax);
                sPass += _randCharacters[p];
            }
            if (iMix < 1)
            {
                sPass = sPass.ToUpper();
            }
            else if (iMix < 2)
            {
                sPass = sPass.ToLower();
            }
            return sPass;
        }
        #endregion
    }
}
